package com.i2bt.util;

/**
 * 
 * Title : 文件大小动态转换工具类
 *
 * Description : 根据文件大小动态转换成kb, mb, gb, tb, pb的字符串返回
 *
 * CreatedTime : 2014-8-25
 *
 * @author wuliao & kakaxi & yi
 *
 * @version 1.0
 *
 */

public class FileSizeConvertUtil {
	
	/*
	 * 转换单位
	 */
	public final static int CONVERT_SIZE = 1024;
	
	/*
	 * 容量倍数代号
	 */
	public final static int INT_KB = 0;
	public final static int INT_MB = 1;
	public final static int INT_GB = 2;
	public final static int INT_TB = 3;
	public final static int INT_PB = 4;
	
	public static int convertCount = INT_KB; // 记录除了多少次
	
	/**
	 * 自动转换文件大小单位
	 * @param fileSize 文件大小以kb为单位的长整形
	 * @return 转换后的文件大小字符串
	 */
	public static String autoConvert(long fileSize) {
		
		int n = (int)sizeNumberConvet(fileSize);
		
		String fileSizeStr = "";
		
		switch (convertCount) {

		case INT_KB : {
			fileSizeStr =  n + "K";
			break;
		}
		
		case  INT_MB : {
			fileSizeStr =  n + "M";
			break;
		}
		
		case INT_GB : {
			fileSizeStr =  n + "G";
			break;
		}
		
		case INT_TB : {
			fileSizeStr =  n + "T";
			break;
		}
		
		case INT_PB : {
			fileSizeStr =  n + "P";
			break;
		}
		
		}

		//重置计数为kb
		convertCount = INT_KB;
		
		//超出了pb
		return fileSizeStr;
	}
	
	/**
	 * 递归除到最比转换单位小为止
	 * @param fileSize 文件大小长整形
	 * @return 比转换单位小的数值
	 */
	private static long sizeNumberConvet(long fileSize) {
		if (fileSize >= CONVERT_SIZE) {
			fileSize /= CONVERT_SIZE;
			convertCount++;
			return sizeNumberConvet(fileSize);
		}
		else {
			return fileSize;
		}
	}
	
}
